const playSignal = (signal = [], audioContext, sampleRate) => {
  const signalLength = signal.length

  const node = audioContext.createBufferSource()

  // 1 channel
  const buffer = audioContext.createBuffer(1, signalLength, sampleRate)

  const data = buffer.getChannelData(0)

  for (let i = 0; i < signalLength; i++) {
    data[i] = signal[i]
  }

  node.buffer = buffer

  node.connect(audioContext.destination)

  node.start(audioContext.currentTime)
}

const loadSound = (path, audioContext) => {
  const request = new XMLHttpRequest()
  request.open('GET', path, true)
  request.responseType = 'arraybuffer'

  const promise = new Promise((resolve, reject) => {
    request.onload = () => {
      audioContext.decodeAudioData(
        request.response,
        buffer => resolve(buffer),
        error => console.error(error)
      )
    }
    request.onerror = error => reject(error)
  })

  request.send()

  return promise
}

const playBuffer = (buffer, audioContext) => {
  const startTime = audioContext.currentTime

  const source = audioContext.createBufferSource()
  source.buffer = buffer

  source.connect(audioContext.destination)

  source.start(startTime)
  source.stop(startTime + 2)
}
